package org.lboot.md.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.stream.StreamUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.md.domain.MarkdownFile;
import org.lboot.md.service.MarkdownCtl;
import org.lboot.md.service.MarkdownFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class MarkdownCtlImpl implements MarkdownCtl {

    MarkdownFileService fileService;


    @SneakyThrows
    @Override
    public ModelAndView preview(String fileKey) {
        MarkdownFile file = fileService.getFile(fileKey);
        //log.info(file.toString());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("mdpreview");
        modelAndView.addObject("file",file);
        return modelAndView;
    }

    @Override
    public ModelAndView edit(String fileKey) {
        MarkdownFile markdownFile = fileService.getFile(fileKey);
        Map<String ,Object> file = BeanUtil.beanToMap(markdownFile);
        // 设置回调地址
        file.put("callbackUrl","/vditor/callback");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("mdeditor");
        modelAndView.addObject("file",file);
        return modelAndView;
    }

    @Override
    public Object editCallback(Map<String, Object> map) {
        log.info("---markdown change callback---");
        // 获取文件key
        String key = map.get("fileKey").toString();
        // 获取文件内容
        String content = map.get("content").toString();
        InputStream inputStream = new ByteArrayInputStream(content.getBytes());
        if (Validator.isNotEmpty(inputStream)){
            fileService.updateFile(key, inputStream);
        }else {
            log.info("传入content为空");
        }
        log.info("---markdown has modified---");
        return true;
    }

    @Override
    public String fileUpload(MultipartFile file) {
        MarkdownFile markdownFile = fileService.uploadFile(file);
        return markdownFile.getUrl();
    }
}
